<?php

if (!defined('IN_SITE')) {
    exit('Access Denied');
}

class ctrl_user_index extends user_index {

    public $info_array = array();
    public $page_array = array();
    public $tree_array = array();

    static function &instance() {
        static $object;
        if (empty($object)) {
            $object = new self();
        }
        return $object;
    }

    /*
     * 	取出一条信息
     */
    public function do_one_info($user_id = '') {
        $info = array();
        if ($user_id) {
            $sql = "SELECT * FROM " . DB::table('user') . " WHERE user_id='" . $user_id . "' LIMIT 1";
            $info = DB::fetch_first($sql);
        }
        return $info;
    }

    /*
     *  删除用户信息 用户基础数据 + 详情数据 一次性提交
     */
    public function do_userdel() {
        global $_G;
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
        
        $return['code']="1";
        if($user_id){
            $effect_row = $this->delete('user', ["user_id" => $user_id], 1);
            if($effect_row){
                $this->delete('user_detail', ["user_id" => $user_id], 1);
                //删除用户对应的角色
                $this->delete('user_role_relation', ["user_id" => $user_id], 1);
                
                //删除用户对应的班级成员表数据
                $this->delete('class_member', ["user_id" => $user_id], 1);
                
                $return['code'] = '0';
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'], 'pc', 'msg_admin', 'admin');
        return false;
    }
    
    /*
     * 导出指定学校的班级class_id
     */
    public function do_classidexport(){
        global $_G;
        //此处接收传递的搜索条件
        $sm_id = isset($_REQUEST['sm_id']) && !empty($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//学校编号sm_id
        $grade_num = isset($_REQUEST['grade_num']) && !empty($_REQUEST['grade_num']) ? $_REQUEST['grade_num'] : '';//年级编号
        
        if($sm_id){
            $whereSql.= " and cm.sm_id = ".$sm_id." ";
        }
        
        if($grade_num){
            $whereSql.= " and cm.grade_num = ".$grade_num." ";
        }
        
        $sql = "select cm.class_id, cm.class_name from ".DB::table('class_main')." as cm where 1 = 1 and cm.isdelete = 0 ".$whereSql;
        
        $sql_result = DB::fetch_all($sql);
        
        $filename = 'classiddc'.date('YmdHis').'.xls'; //设置文件名
        
        $titles = ['班级编号', '班级名称'];
        
        $data = [];
        
        //将上述结果集转换为目标数组
        if(!empty($sql_result) && is_array($sql_result)){
            foreach ($sql_result as $k => $item) {
                $data[$k] = [
                    0 => isset($item['class_id']) ? $item['class_id'] : '',
                    1 => isset($item['class_name']) ? $item['class_name'] : ''
                ];
            }
        }
        
        $xlsData = makeXls($titles, $data);
        
        $target = SITE_ROOT.'data/upload/';
        
        $fp = fopen($target.$filename, 'w');
        //向目标文件写入操作
        fwrite($fp, $xlsData);

        fclose($fp);
        
        $return['code'] = '1';
        //检测是否对应已生成csv文件
        if(is_file($target.$filename)){
            //2017-6-6 11:51:34 此处将该csv文件上传到文件服务器，同时删除本地的文件
            $data = ['filedata'  =>  new CURLFile($target.$filename), 'dir' => '/'];
            $ch = curl_init();

            curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
            curl_setopt($ch, CURLOPT_URL, 'http://101.37.15.34/upload.php');
            curl_setopt($ch, CURLOPT_POST, true );
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

            $res = curl_exec($ch);
            curl_close($ch);

            //此处删除掉本地的文件
            @unlink($target.$filename);

            if($res == 'success'){//成功
               $return['code'] = '0';
               $return['data']['url'] = 'http://fstore.jxzhjy.com/data/upload/'.$filename;
            }
            else{//远程文件上传失败
               $return['code'] = '1';
               $return['data']= [];
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 用户重置密码
     */
    public function do_editpwd(){
        global $_G;
        $return['code'] = "1";
        
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : 0;
        $pwd = isset($_REQUEST['password']) ? $_REQUEST['password'] : '';
        
        if(!$user_id || !$pwd){
            $return['code'] = '2';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        $data['user_password'] = encode_password($pwd);
        $data['modify_dateline'] = TIMESTAMP;
        $where = ['user_id' => $user_id];
        $effect_row = DB::update('user', $data, $where);
        
        if($effect_row){//基本信息修改成功
            $return['code'] = "0";
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'], 'pc', 'msg_admin', 'admin');
        return false;
    }
    
    /*
     * 用户编辑 用户基础数据 + 详情数据 一次性提交
     */
    public function do_useredit() {
        global $_G;
        $return['code']="1";
        $user = isset($_REQUEST['user']) && !empty($_REQUEST['user']) ? $_REQUEST['user'] : [];
        $user_detail = isset($_REQUEST['user_detail']) && !empty($_REQUEST['user_detail']) ? $_REQUEST['user_detail'] : [];
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
        
        $role_id = isset($_REQUEST['role_id']) && !empty($_REQUEST['role_id']) ? $_REQUEST['role_id'] : 21;//默认角色为学生
        
        if($user_id){//传入了user_id
            $check_user['user_name'] = $user['user_name'];
            $check_user['modify_user_id'] = $user_id;
            $check_result = auto_mad('user', 'main', 'check_user_exist', $check_user, 1, 1);//校验用户是否存在
            if(empty($check_result)){
                $data['user_name'] = $user['user_name'];
                if(!empty($user['user_password'])){
                    $data['user_password'] = encode_password($user['user_password']);
                }
                $data['ischeck'] = $user['ischeck'];
                $data['modify_dateline'] = TIMESTAMP;
                $where = ['user_id' => $user_id];
                $effect_row = DB::update('user', $data, $where);
                if($effect_row){//基本信息修改成功
                    if($user_detail){//如果传递进来了对应的用户详情字段则走该段处理
                        $this->edit('user_detail', $user_detail, $where);
                    }
                    
                    //此处修改用户的角色
                    $rdata['role_id'] = $role_id;
                    $rwhere = ['user_id' => $user_id];
                    @DB::update('user_role_relation', $rdata, $rwhere);
                    
                    //2017-6-9 08:46:07 如果传入了class_id的话将该用户同时添加到班级成员表中去
                    if(isset($user_detail['class_id']) && $user_detail['class_id'] && ($role_id == 21)){
                        //先删除旧的关系数据
                        $this->delete('class_member', ["user_id" => $user_id, 'cm_type' => 21], 1);
                        
                        $class_member['class_id'] = $user_detail['class_id'];
                        $class_member['user_id'] = $user_id;
                        $class_member['cm_type'] = 21;
                        $class_member['create_time'] = TIMESTAMP;
                        $class_member['modify_time'] = TIMESTAMP;

                        $this->add('class_member', $class_member);
                    }
                    
                    $return['code']="0";
                }   
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'], 'pc', 'msg_admin', 'admin');
        return false;
    }
    
    /*
     * csv批量注册学生账号
     */
    public function do_studentcsv(){
        global $_G;
        
        @set_time_limit(0);
        @set_magic_quotes_runtime(0);
        @ini_set('memory_limit','2048M');
        //接收参数
        $filepath = isset($_REQUEST['filepath']) && !empty($_REQUEST['filepath']) ? $_REQUEST['filepath'] : '';//上传的csv路径
        if(!$filepath){//如果没有传递过来对应的参数路径
            $return['code'] = '1';
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        //读取csv内容
        $handle = fopen($filepath, 'r'); 

        $result = array();
        $n = 0;
        while($data = fgetcsv($handle, 10000)){
            $num = count($data);
            for ($i = 0;$i < $num;$i++) {
                $result[$n][$i] = iconv('gb2312', 'utf-8', $data[$i]);
            }
            $n++;
        }

        fclose($handle); //关闭指针
        
        $len_result = count($result);
        if($len_result <= 1){
            $return['code'] = '2';//没有数据
            echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
            return false;
        }
        
        unset($result[0]);
        
        $failArr = [];
        
        $totalNum = 0;//共计处理数量
        $okNum = 0;//成功处理数量
        
        //遍历结果集
        foreach ($result as $item) {
            //1.先验证一下角色名称是狗被占用，如果被占用则不能继续
            $data['user_name'] = $item[0];
            $check_result = auto_mad('user', 'main', 'check_user_exist', $data, 1, 1);//校验用户是否存在
            
            if(empty($check_result)){//不存在
                //初始化重置
                $cdata = [];
                $user_detail = [];
                $user_role = [];
                $class_member = [];
                
                $cdata['user_name'] = $item[0];
                $cdata['user_password'] = encode_password(substr($item[0], -6));
                $cdata['create_dateline'] = TIMESTAMP;
                $cdata['modify_dateline'] = TIMESTAMP;
                $insert_id = DB::insert('user', $cdata, true);
                
                if($insert_id){//此处先生成了user表中的数据获得user_id
                    $user_detail['user_realname'] = $item[1];
                    $user_detail['user_nickname'] = $item[1];
                    $user_detail['user_phone'] = $item[2];
                    $user_detail['am_id_1'] = $item[3];
                    $user_detail['am_id_2'] = $item[4];
                    $user_detail['am_id_3'] = $item[5];
                    $user_detail['sm_id'] = $item[6];
                    $user_detail['class_id'] = $item[7];
                    $user_detail['so_id'] = $item[8];
                    $user_detail['user_id'] = $insert_id;
                    $this->add('user_detail', $user_detail);

                    //此处将当前用户绑定角色
                    $user_role['user_id'] = $insert_id;
                    $user_role['role_id'] = 21;
                    $this->add('user_role_relation', $user_role);
                    
                    //2017-6-9 08:46:07 如果传入了class_id的话将该用户同时添加到班级成员表中去
                    if($item[7]){
                        $class_member['class_id'] = $item[7];
                        $class_member['user_id'] = $insert_id;
                        $class_member['cm_type'] = 21;
                        $class_member['create_time'] = TIMESTAMP;
                        $class_member['modify_time'] = TIMESTAMP;
                        
                        $this->add('class_member', $class_member);
                    }
                    
                    $okNum += 1;
                }
            }
            else{
                $failArr[] = $item;
            }
            
            $totalNum += 1;
        }
        
        if($totalNum == $okNum){//全部处理成功
            $return['code'] = '0';
        }
        else{
            $return['code'] = '3';
            
            // 2017-01-06 16:24:19
            // 返回成功个数，失败个数，错误的信息内容重新生成cvs文件下载链接
            $return['data']['total'] = $totalNum;
            $return['data']['success'] = $okNum;
            $return['data']['fail'] = $totalNum - $okNum;
            
            $f = ',';//定义分隔符
        
            //开始组装目标数组
            $filename = 'erroruser'.date('YmdHis').'.csv'; //设置文件名
            $list[] = iconv("utf-8","gb2312", '用户名'.$f.'昵称'.$f.'手机号'.$f.'省份编号'.$f.'市区编号'.$f.'县区编号'.$f.'学校编号'.$f.'班级编号'.$f.'网校编号');

            //将上述结果集转换为目标数组
            if(!empty($failArr) && is_array($failArr)){
                foreach ($failArr as $item) {
                    $list[] = iconv("utf-8","gb2312", $item[0].$f.$item[1].$f.$item[2].$f.$item[3].$f.$item[4].$f.$item[5].$f.$item[6].$f.$item[7].$f.$item[8]);
                }
            }
        
            $target = SITE_ROOT.'data/upload/';
            $fp = fopen($target.$filename, 'w');
            //向目标文件写入操作
            foreach ($list as $line) {
                fputcsv($fp, explode(',', $line));
            }

            fclose($fp);
        
            //检测是否对应已生成csv文件
            if(is_file($target.$filename)){
                $return['data']['url'] = 'http://webapi.jxzhjy.com/data/upload/'.$filename;
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do']);
        return false;
    }
    
    /*
     * 用户新增 用户基础数据 + 详情数据 一次性提交
     */
    public function do_useradd(){
        global $_G;
        $return['code'] = "1";
        $user = isset($_REQUEST['user']) && !empty($_REQUEST['user']) ? $_REQUEST['user'] : [];
        $user_detail = isset($_REQUEST['user_detail']) && !empty($_REQUEST['user_detail']) ? $_REQUEST['user_detail'] : [];
        
        $role_id = isset($_REQUEST['role_id']) && !empty($_REQUEST['role_id']) ? $_REQUEST['role_id'] : 21;//默认角色为学生
        
        //DEBUG 
        $data['user_name'] = $user['user_name'];
        $check_result = auto_mad('user', 'main', 'check_user_exist', $data, 1, 1);//校验用户是否存在
        if ($user && empty($check_result)) {
            $cdata['user_name'] = $user['user_name'];
            if(!empty($user['user_password'])){
                $cdata['user_password'] = encode_password($user['user_password']);
            }
            $cdata['ischeck'] = $user['ischeck'];
            $cdata['create_dateline'] = TIMESTAMP;
            $insert_id = DB::insert('user', $cdata, true);
            if($insert_id){//此处先生成了user表中的数据获得user_id
                if($user_detail){//如果传递进来了对应的用户详情字段则走该段处理
                    $user_detail['user_id'] = $insert_id;
                    $this->add('user_detail', $user_detail);
                }
                
                //此处将当前用户绑定角色
                $user_role['user_id'] = $insert_id;
                $user_role['role_id'] = $role_id;
                $this->add('user_role_relation', $user_role);
                
                //2017-6-9 08:46:07 如果传入了class_id的话将该用户同时添加到班级成员表中去
                if(isset($user_detail['class_id']) && $user_detail['class_id'] && ($role_id == 21)){
                    $class_member['class_id'] = $user_detail['class_id'];
                    $class_member['user_id'] = $insert_id;
                    $class_member['cm_type'] = 21;
                    $class_member['create_time'] = TIMESTAMP;
                    $class_member['modify_time'] = TIMESTAMP;

                    $this->add('class_member', $class_member);
                }
                
                $return['code'] = '0';
                $return['data']['id'] = (string)$insert_id;
            }
        }
        
        echo format_data($return, 'json', $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'], 'pc', 'msg_admin', 'admin');
        return false;
    }
    
    /*
     *  添加系统信息
     */
    public function do_add() {
        global $_G;
        $return['code']="1";
        $issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit'] : '';//csrf 校验标记
        $user = isset($_REQUEST['user']) && !empty($_REQUEST['user']) ? $_REQUEST['user'] : '';
        //DEBUG 
        $data['user_name'] = $user['user_name'];
        $check_result = auto_mad('user', 'main', 'check_user_exist', $data, 1,1);//校验用户是否存在
        if ($user && empty($check_result)) {
            $data['user_name'] = $user['user_name'];
            if (!empty($user['user_password'])) {
                $data['user_password'] = encode_password($user['user_password']);
            }
            $data['ischeck'] = $user['ischeck'];
            $data['create_dateline'] = TIMESTAMP;
            $insert_id = DB::insert('user', $data, true);
            if ($insert_id) {
                $return['code']="0";
            }
        }
        if ($_G['gp_api']) {
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'],'pc','msg_admin','admin');
        }
    }

    /*
     *  编辑系统信息
     */

    public function do_edit() {
        global $_G;
        $return['code']="1";
        $issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit'] : '';//csrf 校验标记
        $user = isset($_REQUEST['user']) && !empty($_REQUEST['user']) ? $_REQUEST['user'] : '';
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
        if ($user_id) {
            $check_user['user_name'] = $user['user_name'];
            $check_user['modify_user_id'] = $user_id;
            $check_result = auto_mad('user', 'main', 'check_user_exist', $check_user, 1,1);//校验用户是否存在
            if(empty($check_result)){
                $data['user_name'] = $user['user_name'];
                if (!empty($user['user_password'])) {
                    $data['user_password'] = encode_password($user['user_password']);
                }
                $data['ischeck'] = $user['ischeck'];
                $data['modify_dateline'] = TIMESTAMP;
                $where = array('user_id' => $user_id);
                $effect_row = DB::update('user', $data, $where);
                if ($effect_row) {
                    $return['code']="0";
                }   
            }
        }
        if ($_G['gp_api']) {
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'],'pc','msg_admin','admin');
        }
    }

    /*
     *  删除系统信息
     */

    public function do_delete() {
        global $_G;
        $user_id = isset($_REQUEST['user_id']) ? $_REQUEST['user_id'] : '';
        if ($user_id) {
            DB::delete("user", array("user_id" => $user_id), $limit = 1);
            //TODO 逻辑删需要创建isdelete字段 0=未删除 1=已删除
            //DB::update("user",array('isdelete'=>1), array("user_id" => $user_id), $limit=1);
            $return['code']="0";
        }else{
            $return['code']="1";
        }
        if ($_G['gp_api']) {
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'],'pc','msg_admin','admin');
        }
    }

    /*
     *  用户编辑个人信息
     */

    public function do_profile() {
        global $_G;
        $issubmit = isset($_REQUEST['issubmit']) && !empty($_REQUEST['issubmit']) ? $_REQUEST['issubmit'] : '';
        $user = isset($_REQUEST['user']) && !empty($_REQUEST['user']) ? $_REQUEST['user'] : '';

        $user_id = $_G['user_id'];
        if ($user_id) {
            if ('1' == $issubmit) {
                $user['modify_dateline'] = TIMESTAMP;
                if (!empty($user['user_password'])) {
                    $user['user_password'] = encode_password($user['user_password']);
                } else {
                    unset($user['user_password']);
                }
                $where = array('user_id' => $user_id);
                $user['email_token_exptime'] = strtotime($user['email_token_exptime']);
                $effect_row = DB::update('user', $user, $where);
                if ($effect_row) {
                    showmessage('操作成功', 'index.php?mod=user&action=index&do=profile');
                } else {
                    showmessage('操作失败', 'index.php?mod=user&action=index&do=profile');
                }
            } else {
                //DEBUG 获取节点信息
                $info = self::do_one_info($user_id);
                unset($info['user_password']);
                include template('user/index/profile');
            }
        } else {
            showmessage('修改信息异常', 'index.php?mod=user&action=index&do=profile');
        }
    }

    /*
     *  用户信息列表
     */

    public function do_index() {
        global $_G;
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;
        $perpage = $limit = isset($_REQUEST['limit']) ? $_REQUEST['limit'] : 10;
        $start = (($page - 1) * $perpage);
        $wheresql = " AND U1.isdelete = 0 ";
        //user
        $user_name = isset($_REQUEST['user_name']) ? $_REQUEST['user_name'] : '';//用户名
        $ischeck = isset($_REQUEST['ischeck']) ? $_REQUEST['ischeck'] : '';//用户是否审核 1 正常 2 待激活 3待审核  4 锁定
        //user_detail
        $am_id_1 = isset($_REQUEST['am_id_1']) ? $_REQUEST['am_id_1'] : '';//所属省编号
        $am_id_2 = isset($_REQUEST['am_id_2']) ? $_REQUEST['am_id_2'] : '';//所属市编号
        $am_id_3 = isset($_REQUEST['am_id_3']) ? $_REQUEST['am_id_3'] : '';//所属县编号
        $sm_id = isset($_REQUEST['sm_id']) ? $_REQUEST['sm_id'] : '';//当前所在学校编号
        $class_id = isset($_REQUEST['class_id']) ? $_REQUEST['class_id'] : '';//当前所在班级编号
        $user_realname = isset($_REQUEST['user_realname']) ? $_REQUEST['user_realname'] : '';//真实姓名
        $user_nickname = isset($_REQUEST['user_nickname']) ? $_REQUEST['user_nickname'] : '';//用户昵称
        $user_phone = isset($_REQUEST['user_phone']) ? $_REQUEST['user_phone'] : '';//用户手机
        //user_role_relation
        $role_id = isset($_REQUEST['role_id']) ? $_REQUEST['role_id'] : '';//用户角色编号
        //user
       
        if($user_name){//如果传递了用户名
            $wheresql.= " AND U1.user_name LIKE '%" . $user_name . "%'";
        }
        if($ischeck){//用户是否审核 1 正常 2 待激活 3待审核  4 锁定
            $wheresql.= " AND U1.ischeck = ".$ischeck;
        }
        //user_detail
        if($am_id_1){//所属省编号
            $wheresql.= " AND U2.am_id_1 = ".$am_id_1;
        }
        if($am_id_2){//所属市编号
            $wheresql.= " AND U2.am_id_2 = ".$am_id_2;
        }
        if($am_id_3){//所属县编号
            $wheresql.= " AND U2.am_id_3 = ".$am_id_3;
        }
        if($sm_id){//当前所在学校编号
            $wheresql.= " AND U2.sm_id = ".$sm_id;
        }
        if($class_id){//当前所在班级编号
            $wheresql.= " AND U2.class_id = ".$class_id;
        }
        if($user_realname){//真实姓名
            $wheresql.= " AND U2.user_realname = '".$user_realname."'";
        }
        if($user_nickname){//用户昵称
            $wheresql.= " AND U2.user_nickname = ".$user_nickname;
        }
        if($user_phone){//用户手机
            $wheresql.= " AND U2.user_phone = ".$user_phone;
        }
        //user_role_relation
        if($role_id){//用户手机
            $wheresql.= " AND U3.role_id = ".$role_id;
        }
       
        // 2017-1-9 08:58:44 改为支持多种查询条件
        $sql_info = "SELECT U1.user_id, U1.user_name, U1.ischeck, U1.create_dateline "
                . "FROM ".DB::table('user')." as U1 "
                . "left join ".DB::table('user_detail')." as U2 on U1.user_id = U2.user_id "
                . "left join ".DB::table('user_role_relation')." as U3 on U1.user_id = U3.user_id "
                . "WHERE 1 = 1 ".$wheresql." ORDER BY U1.user_id DESC ".DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        foreach ($sql_info_result AS $key => $value){
            $user_ids[]=$value['user_id'];
        }
        //增加获取用户 姓名 手机号
        $user_detail_sql = "SELECT * FROM " . DB::table('user_detail') . " WHERE user_id IN (". dimplode($user_ids) .") ORDER BY user_id DESC ";
        $user_detail_result = DB::fetch_all($user_detail_sql);
        foreach ($user_detail_result AS $key => $value){
            $user_detail_array[$value['user_id']]=$value;
        }
        
        //增加获取用户 身份关系
        $user_role_relation_sql = "SELECT user_id, role_id FROM " . DB::table('user_role_relation') . " WHERE user_id IN (". dimplode($user_ids) .")";
        $user_role_relation_result = DB::fetch_all($user_role_relation_sql);
        foreach ($user_role_relation_result AS $key => $value){
            $user_role_array[$value['user_id']]=$value['role_id'];
        }
        //增加获取 身份名称
        $user_role_sql = "SELECT role_id, role_name FROM " . DB::table('user_role') . "";
        $user_role_result = DB::fetch_all($user_role_sql);
        foreach ($user_role_result AS $key => $value){
            $role_array[$value['role_id']] = $value['role_name'];
        }
        
        foreach($sql_info_result AS $key=>$value){
            $sql_info_result[$key]['user_realname']=$user_detail_array[$value['user_id']]['user_realname'];
            $sql_info_result[$key]['user_phone']=$user_detail_array[$value['user_id']]['user_phone'];
            $sql_info_result[$key]['role_id']=$user_role_array[$value['user_id']];
            $sql_info_result[$key]['role_name']=$role_array[$user_role_array[$value['user_id']]];
            
            $sql_info_result[$key]['am_id_1'] = $user_detail_array[$value['user_id']]['am_id_1'];
            $sql_info_result[$key]['am_id_2'] = $user_detail_array[$value['user_id']]['am_id_2'];
            $sql_info_result[$key]['am_id_3'] = $user_detail_array[$value['user_id']]['am_id_3'];
            $sql_info_result[$key]['sm_id'] = $user_detail_array[$value['user_id']]['sm_id'];
            $sql_info_result[$key]['class_id'] = $user_detail_array[$value['user_id']]['class_id'];
            $sql_info_result[$key]['user_realname'] = $user_detail_array[$value['user_id']]['user_realname'];
            $sql_info_result[$key]['user_nickname'] = $user_detail_array[$value['user_id']]['user_nickname'];
            $sql_info_result[$key]['user_phone'] = $user_detail_array[$value['user_id']]['user_phone'];
            $sql_info_result[$key]['phone_validation'] = $user_detail_array[$value['user_id']]['phone_validation'];
            $sql_info_result[$key]['user_avatar'] = !empty($user_detail_array[$value['user_id']]['user_avatar']) ? $user_detail_array[$value['user_id']]['user_avatar'] : $_G['config']['data']['1']['host'].'/data/upload/user_avatar.png';
            $sql_info_result[$key]['user_sign'] = $user_detail_array[$value['user_id']]['user_sign'];
            $sql_info_result[$key]['user_email'] = $user_detail_array[$value['user_id']]['user_email'];
            $sql_info_result[$key]['email_validation'] = $user_detail_array[$value['user_id']]['email_validation'];
            $sql_info_result[$key]['student_no'] = $user_detail_array[$value['user_id']]['student_no'];
            $sql_info_result[$key]['student_school_no'] = $user_detail_array[$value['user_id']]['student_school_no'];
            $sql_info_result[$key]['gender'] = $user_detail_array[$value['user_id']]['gender'];
            $sql_info_result[$key]['qq'] = $user_detail_array[$value['user_id']]['qq'];
            $sql_info_result[$key]['address'] = $user_detail_array[$value['user_id']]['address'];
            $sql_info_result[$key]['about'] = $user_detail_array[$value['user_id']]['about'];
            $sql_info_result[$key]['isdelete'] = $user_detail_array[$value['user_id']]['isdelete'];
            $sql_info_result[$key]['isp'] = $user_detail_array[$value['user_id']]['isp'];
            
            $tmpDesc = $this->one_info('school_main', 'sm_id', $user_detail_array[$value['user_id']]['sm_id']);
            $sql_info_result[$key]['sm_name'] = isset($tmpDesc['sm_name']) ? $tmpDesc['sm_name'] : '';
            $sql_info_result[$key]['sm_type'] = isset($tmpDesc['sm_type']) ? $tmpDesc['sm_type'] : '';
        }
        
        $sql_total_rows =  "SELECT count(*) "
                . "FROM ".DB::table('user')." as U1 "
                . "left join ".DB::table('user_detail')." as U2 on U1.user_id = U2.user_id "
                . "left join ".DB::table('user_role_relation')." as U3 on U1.user_id = U3.user_id "
                . "WHERE 1 = 1 ".$wheresql;
        $sql_total_rows_result = DB::result_first($sql_total_rows);
        $page_result = array(
            'page_now' => $page,
            'total_page' => max(1, ceil($sql_total_rows_result / $perpage)),
            //int 返回结果总数
            'total_rows' => $sql_total_rows_result,
            //array 一页数据数组
            'page_data' => $sql_info_result
        );
        $return['code']="0";
        $return['data']=$page_result;
        if ($_G['gp_api']) {
            echo format_data($return, $_G['gp_api'], $_G['gp_mod'], $_G['gp_action'], $_G['gp_do'],'pc','msg_admin','admin');
        }
    }

    /**
     * 接口 AJAX或外部请求检索数据
     *
     * @param $return_type string json/xml.
     *
     * @return print string json/xml.
     */
    public function do_api() {
        $return = '';
        $page = max(1, intval($_GET['page']));
        $perpage = $limit = 20;
        $start = (($page - 1) * $perpage);
        $keyword = isset($_REQUEST['keyword']) ? $_REQUEST['keyword'] : '';
        $return_type = isset($_REQUEST['return_type']) ? $_REQUEST['return_type'] : 'json';
        $wheresql = "";
        if ($keyword) {
            $wheresql = " WHERE user_realname LIKE '%" . $keyword . "%'";
        }
        $sql_info = "SELECT user_id FROM " . DB::table('user') . " WHERE 1=1 " . $wheresql . " ORDER BY user_id DESC " . DB::limit($start, $limit);
        $sql_info_result = DB::fetch_all($sql_info);
        if ('json' == $return_type) {
            $return = json_encode($sql_info_result);
        } elseif ('xml' == $return_type) {
            $return = array2xml($sql_info_result);
        }
        echo $return;
    }

    /*
     * 	用户登录验证
     */

    public function do_login() {
        global $_G;
        $issubmit = isset($_POST['issubmit']) && !empty($_POST['issubmit']) ? $_POST['issubmit'] : '';
        if ('1' == $issubmit) {
            /* 接收数据 */
            $username = isset($_POST['username']) && !empty($_POST['username']) ? $_POST['username'] : '';
            $password = isset($_POST['password']) && !empty($_POST['password']) ? $_POST['password'] : '';
            $api_client = isset($_POST['api_client']) ? $_POST['api_client'] : '';
            $check_username = DB::result_first("SELECT user_id FROM " . DB::table('user') . " where user_name ='" . $username . "' AND isdelete = 0 LIMIT 1");
            $user_id = DB::result_first("SELECT user_id FROM " . DB::table('user') . " where user_name ='" . $username . "' and user_password ='" . encode_password($password) . "' AND isdelete = 0 LIMIT 1");
            /* 校验数据 */
            if (empty($check_username)) {
                showmessage(lang('core', 'username_invalid'), 'index.php');
            }
            if (empty($user_id)) {
                showmessage(lang('core', 'password_invalid'), 'index.php');
            }
            $user['user_id'] = $user_id;
            @ext::synlogin($user, $user);
            @header('Location: index.php?mod=index&action=index&do=index');
        } else {
            include template('user/index/login');
        }
    }

    /*
     * 	用户注销退出
     */

    public function do_logout() {
        ext::synlogout();
        @header('Location: index.php');
    }

    /*
     * ajax 返回信息
     */

    public function return_json($error, $message, $output = 1) {
        $return_array = array(
            "error" => $error,
            "message" => $message
        );
        if ($output) {
            echo json_ext($return_array);
            die;
        } else {
            return json_ext($return_array);
        }
    }

}

?>